package com.brick.controller;

import com.brick.entity.*;
import com.brick.service.*;
import com.brick.util.ResultUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

import static com.brick.util.Util.util;

@RequestMapping("/api/orderServlet")
@RestController
public class OrderController {
    @Autowired
    OrderService orderService;
    @Autowired
    CommodityService commodityService;
    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    ShoppingCarService shoppingCarService;
    @Autowired
    AccountService accountService;
    @Autowired
    AccountLogService accountLogService;

    @RequestMapping("/getOrder")
    public Result<List<Order>> getOrder( @RequestBody Order order, BindingResult bindingResult){
        PageHelper.startPage(order.getPageNum(),order.getPageSize());

        List<Order> accountList = orderService.selectAll(order);
        //得到分页的结果对象
        PageInfo<Order> pageInfo = new PageInfo<>(accountList);
        //得到分页中的Order条目对象
        List<Order> pageList = pageInfo.getList();

        for (Order ele:pageList) {
            for (OrderDetail detail:ele.getOrderDetailList()) {
                Commodity commodity = new Commodity();
                commodity.setId(detail.getCommodityId());
                List<Commodity> commodityList = commodityService.selectAll(commodity);
                detail.setCommodity(commodityList.get(0));
            }
        }
        if (bindingResult.hasErrors()){
            return ResultUtil.error(0,bindingResult.getFieldError().getDefaultMessage());
        }
        return ResultUtil.success(pageList, pageInfo.getTotal());
    }
    @Transactional
    @RequestMapping("/addOrder")
    public Result addOrder(@RequestBody Order order, BindingResult bindingResult){
        try{
            Double count = 0.0;// 该订单总价
            List<OrderDetail> orderDetailList = order.getOrderDetailList();
            // 判断用户金额是否足够
            for (OrderDetail detail : orderDetailList) {
                count += detail.getNumber()*detail.getRealPrice();
            }
            Account account = accountService.selectAll(order.getUserId());
            if (account.getBalance()< count){
                return ResultUtil.error(0,"金额不足，请充值！");
            }
            // 添加订单
            order.setId(util.getUUID());
            order.setDateline(util.getDateNow());
            order.setOrderState(1);
            order.setState(1);

            // 扣款
            account.setUpdateBalance(-1 * count);
            accountService.update(account);
            // 扣款明细
            AccountLog accountLog = new AccountLog();
            accountLog.setId(util.getUUID());
            accountLog.setBalance(-1 * count);
            accountLog.setDateline(util.getDateNow());
            accountLog.setOrderId(order.getId());
            accountLog.setUserId(order.getUserId());
            accountLog.setState(1);
            accountLogService.insert(accountLog);

            for (OrderDetail detail : orderDetailList) {
                // 添加订单详情
                OrderDetail orderDetail = detail;
                orderDetail.setId(util.getUUID());
                orderDetail.setOrderId(order.getId());
                orderDetail.setTotal(orderDetail.getRealPrice() * orderDetail.getNumber());
                orderDetail.setState(1);
                orderDetailService.insert(orderDetail);


                // 修改商品数量
                Commodity commodity = new Commodity();
                commodity.setId(orderDetail.getCommodityId());
                commodity.setUpdateNumber(orderDetail.getNumber() * -1);
                commodityService.update(commodity);

                // 修改购物车商品状态
                ShoppingCart shoppingCart = new ShoppingCart();
                shoppingCart.setOrderId(orderDetail.getCommodityId());
                shoppingCart.setState(2);
                shoppingCarService.update(shoppingCart);
            }
            return ResultUtil.success(orderService.insert(order));
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(0,e.getMessage());
        }

    }

    @RequestMapping("/updateOrder")
    public Result updateOrder(@RequestBody Order order, BindingResult bindingResult){
        int i = 1;
        if (bindingResult.hasErrors()){
            return ResultUtil.error(0,bindingResult.getFieldError().getDefaultMessage());
        }
        return ResultUtil.success(orderService.update(order));
    }
}
